package cn.taleo.common.utils;


import com.google.common.annotations.VisibleForTesting;
import lombok.Value;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.sql.Timestamp;

@Slf4j
public class ReflectionUtils {
    public static String fatherAndSonFeild(Object obj){
        //0.空值判断
        if(obj==null){
            return null;
        }
        //1.子类字符串
        Class  classInfo = obj.getClass();
        Field[] son = classInfo.getDeclaredFields();
        String s1=getFields(son);
        //2.父类字符串
        Field[] father = classInfo.getSuperclass().getDeclaredFields();
        String s2=getFields(father);
        return s1+","+s2;
    }

    public  static String getFields(Field[] fields){
        //1.stringbuffer
        StringBuffer sb = new StringBuffer();
        //2.拼接,结尾不要
        for (int i=0;i<fields.length;i++){
            sb.append(fields[i].getName());
            if (i<fields.length-1){
                sb.append(",");
            }
        }
        //3.转字符串
        return  sb.toString();
    }

    public static String fatherAndSonFeildValue(Object obj){
        //0非空判断
        if(obj==null){
            return  null;
        }
        //1.子类值
        Class calssInfo = obj.getClass();
        Field[] sons = calssInfo.getDeclaredFields();
        String s1=getFieldValues(obj,sons);
        //2,基础值
        Field[] fathers = calssInfo.getSuperclass().getDeclaredFields();
        String s2=getFieldValues(obj,fathers);
        return s1+","+s2;
    }

    public  static  String getFieldValues(Object obj,Field[] fields){
        //0.stringbuff
        StringBuffer sb = new StringBuffer();
        //1.遍历取值
        for (int i=0;i<fields.length;i++) {
            try {
                //2.根据username得到"张三"
                Field f=fields[i];
                fields[i].setAccessible(true);
                Object value = f.get(obj);
                //旗子转换为想要的
                Boolean flag = false;
                if (value != null && (value instanceof String || value instanceof Timestamp)) {
                    flag = true;
                }
                //3.","拼接,末尾没有
                if (flag) {
                    sb.append("'");
                    sb.append(value);
                    sb.append("'");
                }
                if (i < fields.length - 1) {
                    sb.append(",");
                }

            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

}
